//
//  ShopSelectViewController.swift
//  miaoyin
//
//  Created by David on 2017/3/7.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit
import CoreLocation
class ShopSelectViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CLLocationManagerDelegate {
    
    var step0VC: UIViewController?
    
    var tableView: UITableView!
    
    var shopList: NSArray?
    
    var currentLocation: String?
    
    var filesInfos: NSArray?
    
    var locateMan: CLLocationManager!
    var locating = false
    var locateBtn: UIButton!
    var locatingSpinner: UIActivityIndicatorView!
    var locationLabel: UILabel!
    
    convenience init(files: NSArray){
        self.init()
        filesInfos = files
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "选择商家"
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "返回", style: .plain, target: nil, action: nil)
        let locationDefault = UserDefaults.standard.object(forKey: "location") as? String
        if locationDefault != nil {
            currentLocation = locationDefault
        }
        
        tableView = UITableView(frame: view.frame, style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
        
        locationLabel = UILabel(frame: CGRect(x: 52, y: 8, width: view.bounds.width - 100, height: 28))
        locationLabel.text = "正在定位"
        if currentLocation != nil{
            locationLabel.text = currentLocation
        }
        
        locateBtn = UIButton(type: .system)
        locateBtn.frame = CGRect(x: view.bounds.width - 40, y: 8, width: 32, height: 28)
        locateBtn.setTitle("定位", for: UIControlState())
        locateBtn.addTarget(self, action: #selector(ShopSelectViewController.getLocation), for: .touchUpInside)
        
        locatingSpinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        locatingSpinner.center = locateBtn.center
        
        getLocation()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if shopList != nil{
            if shopList!.count > 0{
                return shopList!.count + 1
            }
            
        }
        return 2
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 44
        }else{
            return 88
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "shop")
        
        if indexPath.row == 0{
            
            let locaIcon = UIImageView(frame: CGRect(x: 16, y: 8, width: 28, height: 28))
            locaIcon.image = UIImage(named: "address")
            cell.addSubview(locaIcon)
            
            
            
            cell.addSubview(locationLabel)
            cell.addSubview(locateBtn)
            cell.addSubview(locatingSpinner)
            
            //            let selectBtn = UIButton(type: .System)
            //            selectBtn.frame = CGRect(x: view.bounds.width - 80, y: 8, width: 72, height: 28)
            //            selectBtn.setTitle("手动选择", forState: .Normal)
            //            cell.addSubview(selectBtn)
            
        }else{
            var empty = true
            if shopList != nil{
                if shopList!.count > 0{
                    empty = false
                    
                    
                    let shopInfo = shopList?.object(at: indexPath.row - 1) as? NSDictionary
                    
                    let shopItem = shopInfo//shopInfo.object(at: 0) as! NSDictionary
                    
                    let shopName = shopItem?.object(forKey: "nickname") as? String
                    let shopImage = shopItem?.object(forKey: "logo") as? String
                    let shopDistance = shopItem?.object(forKey: "distance") as? String
                    
                    var shopRate = shopItem?.object(forKey: "star") as? Double
                    if shopRate == nil{
                        let shopRateStr = shopItem?.object(forKey: "star") as? String
                        if shopRateStr != nil{
                            shopRate = Double(shopRateStr!)
                        }
                    }
                    
                    var shopSale = shopItem?.object(forKey: "month_num") as? Int
                    if shopSale == nil{
                        let shopSaleStr = shopItem?.object(forKey: "month_num") as? String
                        if shopSaleStr != nil {
                            shopSale = Int(shopSaleStr!)
                        }
                    }
                    
                    let minPrice = shopItem?.object(forKey: "min_price") as? String
                    let maxPrice = shopItem?.object(forKey: "max_price") as? String
//                    let minPrice = 0.0
//                    let maxPrice = 0.0
                    
//                    let prices = shopInfo?.object(forKey: "price") as? NSDictionary
//                    //print(prices)
//                    if prices != nil{
//                        var minPrice = Double(MAXFLOAT)
//                        var maxPrice = 0.0
//                        for item in prices!.allValues{
//                            let priceInfo = item as! NSDictionary
//                            let priceStr = priceInfo.object(forKey: "price") as? String
//                            if priceStr != nil{
//                                let price = Double(priceStr!)
//                                if price != nil {
//                                    if price! < minPrice{
//                                        minPrice = price!
//                                    }
//                                    if price! > maxPrice{
//                                        maxPrice = price!
//                                    }
//                                }
//                            }
//                            
//                        }
//                    }
                    
                    
                    let icon = UIImageView(frame: CGRect(x: 16, y: 8, width: 72, height: 72))
                    icon.backgroundColor = UIColor.gray
                    cell.addSubview(icon)
                    
                    let nameLabel = UILabel(frame: CGRect(x: 96, y: 8, width: view.bounds.width - 96 - 72, height: 20))
                    cell.addSubview(nameLabel)
                    
                    let distanceLabel = UILabel(frame: CGRect(x: view.bounds.width - 64, y: 8, width: 56, height: 20))
                    distanceLabel.textAlignment = .right
                    distanceLabel.textColor = UIColor.gray
                    distanceLabel.font = UIFont.systemFont(ofSize: 12)
                    cell.addSubview(distanceLabel)
                    
                    let rate = UIView(frame: CGRect(x: 96, y: 36, width: view.bounds.width - 104, height: 12))
                    cell.addSubview(rate)
                    
                    let rateLabel = UILabel(frame: CGRect(x: 70, y: 0, width: rate.bounds.width - 78, height: 12))
                    rateLabel.font = UIFont.systemFont(ofSize: 12)
                    rateLabel.textColor = UIColor.gray
                    rate.addSubview(rateLabel)
                    
                    
                    if shopRate != nil{
                        let star = shopRate!
                        for i in 0..<5 {
                            let starIcon = UIImageView(frame: CGRect(x: CGFloat(i)*14, y: 0, width: 12, height: 12))
                            if star - Double(i) >= 1{
                                
                                starIcon.image = #imageLiteral(resourceName: "star")
                            }else if star - Double(i) >= 0.5{
                                starIcon.image = #imageLiteral(resourceName: "star_half")
                            }else{
                                starIcon.image = #imageLiteral(resourceName: "star_gray")
                            }
                            rate.addSubview(starIcon)
                        }
                        
                        rateLabel.text = "\(String(format: "%0.1lf", star))  "
                        
                        
                    }
                    
                    
                    if shopSale != nil{
                        if shopRate != nil{
                            rateLabel.text! += "月销"
                        }else{
                            rateLabel.center.x -= 70
                            rateLabel.text = "月销"
                            
                        }
                        
                        if shopSale! >= 999 {
                            rateLabel.text! += "999+"
                        }else{
                            rateLabel.text! += "\(shopSale!)"
                        }
                    }
                    
                    var extent = shopInfo?.object(forKey: "is_extend") as? Int
                    if extent == nil {
                        let extentStr = shopInfo?.object(forKey: "is_extend") as? String
                        if extentStr != nil{
                            extent = Int(extentStr!)
                        }
                        
                    }
                    
                    if extent == 1 {
                        if rateLabel.text != nil{
                            if rateLabel.text != "" {
                                rateLabel.text! += "  推广"
                            }else{
                                rateLabel.center.x -= 70
                                rateLabel.text = "  推广"
                            }
                        }else{
                            rateLabel.center.x -= 70
                            rateLabel.text = "  推广"
                        }
                    }
                    
                    
                    let subLabel = UILabel(frame: CGRect(x: 96, y: 56, width: view.bounds.width - 104, height: 24))
                    subLabel.textColor = UIColor.orange
                    cell.addSubview(subLabel)
                    
                    
                    //MARK: 最高最低价格
                    if minPrice == maxPrice {
                        subLabel.text = "￥\(minPrice ?? maxPrice ?? "0.00")"
                    }else{
                        subLabel.text = "￥\(minPrice ?? "0.00") ~ \(maxPrice ?? "0.00")"
                    }
                    
                    if shopImage != nil{
                        let imageURL = URL(string: shopImage!)
                        if imageURL != nil{
                            URLSession.shared.dataTask(with: imageURL!, completionHandler: { (data:Data?, resp:URLResponse?, err:Error?) in
                                if err == nil{
                                    if data != nil{
                                        let image = UIImage(data: data!)
                                        DispatchQueue.main.async {
                                            icon.image = image
                                        }
                                        
                                    }
                                }
                            }).resume()
                        }
                    }
                    
                    nameLabel.text = shopName
                    
                    if shopDistance != nil{
                        distanceLabel.text = "\(shopDistance!)m"
                    }
                    
                    
                    
                    
                }
            }
            
            if empty {
                let emptyLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
                emptyLabel.textAlignment = .center
                emptyLabel.text = "暂无可选商家"
                cell.addSubview(emptyLabel)
                
                
            }
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.row > 0{
            if shopList != nil {
                if shopList!.count > 0{
                    let thisShopInfo = shopList?.object(at: indexPath.row - 1) as? NSDictionary
                    if filesInfos != nil{
                        let ordVC = OrderSumupViewController(files: filesInfos!, shopInfo: thisShopInfo)
                        ordVC.step0VC = self.step0VC
                        navigationController?.pushViewController(ordVC, animated: true)
                    }
                    
                }
            }
            
        }
    }
    
    func getLocation(){
        if !locating {
            if CLLocationManager.locationServicesEnabled(){
                locateMan = CLLocationManager()
                locateMan.delegate = self
                
                locateMan.requestWhenInUseAuthorization()
                locateMan.startUpdatingLocation()
                locateBtn.alpha = 0
                locatingSpinner.startAnimating()
                locating = true
            }else{
//                UIAlertView(title: "定位不可用", message: "请前往设置->隐私->定位服务，打开定位服务，并允许\(Fatcat.PRODUCT_NAME)使用定位服务。", delegate: nil, cancelButtonTitle: "OK").show()
                let alert = UIAlertController(title: "定位不可用", message: "请前往设置->隐私->定位服务，打开定位服务，并允许\(Fatcat.PRODUCT_NAME)使用定位服务。", preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                present(alert, animated: true, completion: nil)
            }
        }
        
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        manager.stopUpdatingLocation()
        if self.locating{
            if locations.count > 0{
                self.locating = false
                
                let longitude = locations.last!.coordinate.longitude
                let latitude = locations.last!.coordinate.latitude
                
                let position = "\(longitude),\(latitude)"
                print(position)
                // MARK: 请求服务器，处理返回的列表
                let paperType = (filesInfos?.firstObject as? NSDictionary)?.object(forKey: "paperOption") as? FCPrintPaperType ?? .blackWhiteSingle
                var p_t = ""
                switch paperType {
                case .blackWhiteSingle:
                    p_t = "bsingle"
                    break
                case .blackWhiteDouble:
                    p_t = "bdouble"
                    break
                case .colorSingle:
                    p_t = "csingle"
                    break
                case .colorDouble:
                    p_t = "cdouble"
                    break
                }//118.094784,24.590113
                let resq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=business&a=businessList&l=\(position)&t=\(p_t)")!)
//                let resq = URLRequest(url: URL(string: "http://114.215.105.95/print/index.php?m=admin&c=business&a=businessList&l=113.307522,22.048477&d=100000")!)
//                let resq = URLRequest(url: URL(string: "https://www.aimiaoyin.com/print/?m=admin&c=business&a=businessList&l=118.097150,24.582520&d=100000&t=bsingle")!)
                
                URLSession.shared.dataTask(with: resq, completionHandler: { (data:Data?, resp:URLResponse?, err:Error?) in
                    do{
                        if err != nil{
                            throw err!
                        }
                        
                        print(String(data: data!, encoding: .utf8) ?? "data str nil")
                        
                        let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                        self.shopList = jsonObj?.object(forKey: "data") as? NSArray
                        
                        
                        
                        DispatchQueue.main.async {
                            self.tableView.reloadData()
                        }
                        
                    }catch let ex{
                        print(ex)
                        let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                        DispatchQueue.main.async {
                            self.present(alert, animated: true, completion: nil)
                        }
                        
                    }
                }).resume()
                
                
                var keywords = ""
                
                let amapURL = URL(string: "https://restapi.amap.com/v3/geocode/regeo?key=\(Fatcat.AMAP_API_KEY)&location=\(position)&poitype=&radius=1000&extensions=all&batch=false&roadlevel=0")
                let amapResq = URLRequest(url: amapURL!)
                URLSession.shared.dataTask(with: amapResq, completionHandler: { (data:Data?, resp:URLResponse?, err:Error?) in
                    if err == nil {
                        if data != nil{
                            //                                    print(NSString(data: data!, encoding: NSUTF8StringEncoding))
                            let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                            if jsonObj != nil {
                                let jsonDic = jsonObj as? NSDictionary
                                if jsonDic != nil{
                                    let status = jsonDic?.object(forKey: "status") as! String
                                    if status == "1" {
                                        let region = jsonDic?.object(forKey: "regeocode") as! NSDictionary
                                        let pois = region.object(forKey: "pois") as! NSArray
                                        let firstPos = pois.object(at: 0) as! NSDictionary
                                        keywords = firstPos.object(forKey: "name") as! String
                                        DispatchQueue.main.async(execute: {
                                            self.currentLocation = keywords
                                            self.locationLabel.text = self.currentLocation
                                            self.locateBtn.alpha = 1
                                            self.locatingSpinner.stopAnimating()
                                        })
                                        
                                        
                                        //                                                self.shopList = NSArray(array: fakeData)
                                    }
                                }
                            }
                        }
                    }
                    
                    /*
                     // 本地假数据
                     let filePath = NSBundle.mainBundle().pathForResource("temp", ofType: ".json")
                     if filePath != nil{
                     let jsonStr = NSData(contentsOfFile: filePath!)
                     if jsonStr != nil{
                     let jsonObj = try? NSJSONSerialization.JSONObjectWithData(jsonStr!, options: .AllowFragments)
                     if jsonObj != nil{
                     let jsonDic = jsonObj as? NSDictionary
                     //                                        print(jsonDic)
                     if jsonDic != nil{
                     let returnData = jsonDic?.objectForKey("data") as? NSDictionary
                     if returnData != nil{
                     //                                                print(returnData)
                     
                     self.shopList = NSArray(array: returnData!.allValues)
                     
                     dispatch_async(dispatch_get_main_queue(), {
                     self.locateBtn.alpha = 1
                     self.locatingSpinner.stopAnimating()
                     
                     self.tableView.reloadData()
                     })
                     
                     
                     }
                     
                     }
                     
                     }
                     }
                     
                     }
                     */
                    /*
                    var businessResq = URLRequest(url: URL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
                    businessResq.httpMethod = "POST"
                    //
                    let kvString = "act=businessList&lotude=\(String(format: "%.8lf", longitude))&latude=\(String(format: "%.8lf", latitude))&keywords="
                    print(kvString)
                    businessResq.httpBody = kvString.data(using: String.Encoding.utf8)
                    
                    URLSession.shared.dataTask(with: businessResq, completionHandler: { (data:Data?, resq:URLResponse?, err:Error?) in
                        if err == nil{
                            if data != nil{
                                print(String(data: data!, encoding: String.Encoding.utf8) ?? "data nil")
                                let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                                if jsonObj != nil{
                                    let jsonDic = jsonObj as? NSDictionary
                                    if jsonDic != nil {
                                        DispatchQueue.main.async(execute: {
                                            self.locateBtn.alpha = 1
                                            self.locatingSpinner.stopAnimating()
                                        })
                                        let returnData = jsonDic?.object(forKey: "data") as? NSDictionary
                                        if returnData != nil{
                                            print(returnData ?? "nil")
                                            self.shopList = NSArray(array: returnData!.allValues)
                                            
                                            DispatchQueue.main.async(execute: {
                                                self.locateBtn.alpha = 1
                                                self.locatingSpinner.stopAnimating()
                                                
                                                self.tableView.reloadData()
                                            })
                                        }
                                    }
                                }
                            }
                        }
                    }).resume()*/
                    
                }).resume()
                
                
                
                //                        let fakeData = NSMutableArray()
                //                        let fakeShop = NSMutableDictionary()
                //                        fakeShop.setValue("商家名称", forKey: "shop_name")
                //                        fakeShop.setValue("http://", forKey: "image")
                //                        fakeShop.setValue(233, forKey: "distance")
                //                        fakeShop.setValue(4.5, forKey: "rate")
                //                        fakeShop.setValue(233, forKey: "sale")
                //
                //                        let price = NSMutableArray()
                //                        price.addObject(["single_blackwhite":0.1])
                //                        price.addObject(["single_color":1.0])
                //                        fakeShop.setValue(price, forKey: "price")
                ////                        fakeShop.setValue(0.1, forKey: "min_price")
                ////                        fakeShop.setValue(1.0, forKey: "max_price")
                //                        fakeShop.setValue("XX省XX市XX区XX镇XXXXXXXX附近", forKey: "address")
                //                        fakeShop.setValue("12345678910", forKey: "phone")
                //                        fakeShop.setValue("商家描述，可能有好多行，需要动态调整高度，具体是先在init的时候，计算好文字的高度，然后利用代理设置第0节第3行（就是现在你在看的这一行）的高度，然后还要设置这个Label的高度，要一致，而且设置他多行显示，否则默认是单行的。", forKey: "description")
                //
                //                        fakeData.addObject(fakeShop)
                //
                //
                //
                //                        self.shopList = NSArray(array: fakeData)
                
                //AMR: 写死计时演示
                //                        if #available(iOS 10.0, *) {
                //                            NSTimer.scheduledTimerWithTimeInterval(3, repeats: false, block: { (timer) in
                //                                dispatch_async(dispatch_get_main_queue(), {
                //
                //                                    self.locateBtn.alpha = 1
                //                                    self.locatingSpinner.stopAnimating()
                //                                    //self.locationLabel.text = self.currentLocation
                //                                    self.tableView.reloadData()
                //                                })
                //                            })
                //                        } else {
                //                            dispatch_async(dispatch_get_main_queue(), {
                //
                //                                self.locateBtn.alpha = 1
                //                                self.locatingSpinner.stopAnimating()
                //
                //                                self.tableView.reloadData()
                //                            })
                //                        }
                
            }
        }
    }
    

    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
